<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 页面上方工具条 -->
      <PageTools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import?type=employee')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportData"
          >导出</el-button>
          <el-button
            :disabled="!checkPermission('POINT-USER-ADD')"
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>
      <!-- 页面下方的内容 -->
      <el-card>
        <el-table :data="list" border>
          <!-- <el-table-column label="序号" type="index" /> -->
          <el-table-column label="序号">
            <template slot-scope="{ $index }">{{
              (pageSetting.page - 1) * pageSetting.size + 1 + $index
            }}</template>
          </el-table-column>
          <el-table-column label="头像">
            <template slot-scope="{ row }">
              <img
                v-imageerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                @click="
                  row.staffPhoto
                    ? popCode(row.staffPhoto)
                    : (showCodeDialog = false)
                "
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                :disabled="!checkPermission('point-user-delete')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageSetting.total"
            :page-size="pageSetting.size"
            :page-sizes="[2, 5, 10, 20, 50]"
            @current-change="currentChange"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" @addEmployee="getUserList" />
      <AssignRole ref="editRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQRcode">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
import { formatDate } from '@/filters'

import { getUserList, delEmployee } from '@/api/employees'
import EmploymentEnum from '@/api/constant/employees'

import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      showRoleDialog: false,
      showCodeDialog: false,
      userId: '',
      imageUrl: '',
      showDialog: false,
      list: [],
      pageSetting: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async editRole(userId) {
      this.userId = userId
      await this.$refs.editRole.getUserDetailById(this.userId)
      this.showRoleDialog = true
    },
    popCode(url) {
      // 1. 弹出窗口
      // 2. 把当前点击的图片地址记录下来
      this.showCodeDialog = true
      this.imageUrl = url
    },
    showQRcode() {
      // 转换并显示二维码
      QRcode.toCanvas(this.$refs.myCanvas, this.imageUrl)
    },
    async exportData() {
      // 创建枚举, 描述中文表头和英文字段名之间的关系
      const headersEnum = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 利用枚举数据, 创建表头数组
      const header = Object.keys(headersEnum)

      // 获取所有的员工数据
      const pageSetting = {
        page: 1,
        size: this.pageSetting.total
      }
      const { rows } = await getUserList(pageSetting)

      // 映射由对象组成的行数据, 变为一个个员工数组
      const data = rows.map((item) => {
        // 遍历时拿到一个个员工对象, 通过函数转成数组
        return this.obj2Array(item, headersEnum)
      })

      // 异步引入导出库
      const excel = await import('@/vendor/Export2Excel')
      // 利用到出库创建 excel 文件
      excel.export_json_to_excel({
        header,
        data
      })
    },
    obj2Array(item, dictionary) {
      // 本来是对象, 想要转成数组, 所以创建一个新数组准备存放
      const array = []

      for (const key in dictionary) {
        // 遍历枚举字典, 获得一个个字段名,并取出数据
        const enKey = dictionary[key]
        let value = item[enKey]
        // 之前的转换, 直接将 value 放了出去
        // 如果数据处理的是事件或者聘用形式, 需要额外处理
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }
        // 如果是聘用形式的数据. 去全局枚举中找到对应的值替换回来
        if (enKey === 'formOfEmployment') {
          const obj = EmploymentEnum.hireType.find((item) => item.id === value)
          value = obj ? obj.value : '不确定的临时工'
        }
        // 推入数组中
        array.push(value)
      }
      // 返回结果
      return array
    },
    async getUserList() {
      const { rows, total } = await getUserList(this.pageSetting)
      this.pageSetting.total = total
      rows.shift()
      this.list = rows
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getUserList()
    },
    sizeChange(newSize) {
      this.pageSetting.size = newSize
      this.getUserList()
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmploymentEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '其他'
    },
    async delEmployee(id) {
      try {
        await this.$confirm('请确认删除该员工')
        await delEmployee(id)
        await this.getUserList()
        this.$message.success('成功删除员工')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
</style>
